package fr.cephb.socialsnp.webapp.form;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class FormBean
	{
	private Map<String, FormParam> id2param=new HashMap<String, FormParam>();
	
	public FormBean()
		{
		}
	
	public void addParam(FormParam param)
		{
		if(id2param.containsKey(param.getName()))
			{
			throw new IllegalArgumentException("param "+param.getName()+" defined twice");
			}
		this.id2param.put(param.getName(), param);
		}
	
	public boolean validate(HttpServletRequest req,HttpServletResponse res) throws ServletException
		{
		for(String name: this.id2param.keySet())
			{
			FormParam param= this.id2param.get(name);
			param.validate(req);
			}
		return isValid();
		}
	
	public boolean isValid()
		{
		for(FormParam param:this.id2param.values())
			{
			if(!param.getErrors().isEmpty()) return false;
			}
		return true;
		}
	
	public String getValue(String name)
		{
		FormParam p= this.id2param.get(name);
		if(p==null) throw new IllegalArgumentException("param "+name+" was not registered");
		return p.getValue();
		}
	
	public Set<ErrorMessage> getErrorMessages()
		{
		Set<ErrorMessage> errors= new HashSet<ErrorMessage>();
		for(FormParam param:this.id2param.values())
			{
			errors.addAll(param.getErrors());
			}
		return errors;
		}
	
	public String listErrors()
		{
		Set<ErrorMessage> msg= getErrorMessages();
		if(msg.isEmpty()) return "";
		StringBuilder b= new StringBuilder("<ul>");
		for(ErrorMessage err:msg)
			{
			b.append("<li>").append(err.getMessage()).append("</li>");
			}
		return b.append("</ul>").toString();
		}
	
	}
